<template>
  <view class="container">
    <!-- 商品图片 -->
    <view class="image-container">
      <image 
        :src="processedMainImage" 
        class="product-image" 
        mode="widthFix"
        @click="previewImage(processedMainImage)"
        v-if="detail.img && detail.img !== ''">
      </image>
    </view>

    <!-- 商品信息卡片 (悬浮在图片上) -->
    <view class="product-card">
      <view class="product-title">{{ detail.title || '未知商品' }}</view>
      
      <view class="product-sales">月售{{ detail.quantity || 0 }}笔</view>
      
      <view class="product-price-row">
        <view class="price-section">
          <text class="price">￥{{ detail.price || 0 }}</text>
        </view>
        <view class="add-to-cart" @click="addToCart">
          <text class="add-text">加入购物车</text>
        </view>
      </view>
    </view>

    <!-- 商品详情 -->
    <view class="product-description">
      <view class="desc-title">商品详情</view>
      <view class="desc-content">{{ detail.desc || '暂无详情' }}</view>
    </view>

    <!-- 更多推荐 -->
    <view class="recommend-section">
      <view class="section-title">更多推荐</view>
      <view class="waterfall-content">
        <view class="waterfall-column" :style="{ width: columnWidth + 'px' }">
          <view
            class="waterfall-item"
            v-for="(item, index) in leftColumn"
            :key="'left' + index"
            @click="switchToProduct(item.id)"
          >
            <image :src="getProductImage(item)" class="item-image" v-if="getProductImage(item) && getProductImage(item) !== ''"></image>
            <image 
              src="" 
              class="item-image"
              v-else>
            </image>
            <view class="item-info">
              <text class="item-title">{{ getProductTitle(item) }}</text>
              <view class="item-details-container">
                <text class="item-notice">{{ getProductNotice(item) }}</text>
                <text class="item-quantity">已售: {{ getProductQuantity(item) }}</text>
              </view>
              <view class="item-price-container">
                <text class="item-price">￥{{ getProductPrice(item) }}</text>
                <text class="item-original-price"
                  >￥{{ getProductOriginalPrice(item) }}</text
                >
              </view>
            </view>
          </view>
        </view>
        <view class="waterfall-column" :style="{ width: columnWidth + 'px' }">
          <view
            class="waterfall-item"
            v-for="(item, index) in rightColumn"
            :key="'right' + index"
            @click="switchToProduct(item.id)"
          >
            <image :src="getProductImage(item)" class="item-image" v-if="getProductImage(item) && getProductImage(item) !== ''"></image>
            <image 
              src="" 
              class="item-image"
              v-else>
            </image>
            <view class="item-info">
              <text class="item-title">{{ getProductTitle(item) }}</text>
              <view class="item-details-container">
                <text class="item-notice">{{ getProductNotice(item) }}</text>
                <text class="item-quantity">销量: {{ getProductQuantity(item) }}</text>
              </view>
              <view class="item-price-container">
                <text class="item-price">￥{{ getProductPrice(item) }}</text>
                <text class="item-original-price"
                  >￥{{ getProductOriginalPrice(item) }}</text
                >
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 底部操作按钮 -->
    <view class="footer_box">
      <view class="operate_box">
        <view class="goods_actions" @click="ToCart()">
          <uni-icons type="cart-filled" size="40" color="#999999"></uni-icons>
        </view>
        <view class="goods_actions" @click="toShop()">
          <uni-icons type="shop-filled" size="40" color="#999999"></uni-icons>
        </view>
      </view>

      <view class="buyButton_box">
        <view class="buy_shop">
          <button @click="handleBuyNow" class="buy-now-btn">立即购买</button>
        </view>
      </view>
    </view>
    
    <view class="footer-placeholder"></view>
  </view>
</template>

<script>
import uniIcons from "@/uni_modules/uni-icons/components/uni-icons/uni-icons.vue";
import config from "@/static/config.js";
import { foodAPI } from "@/static/indexAPI.js";

export default {
  components: {
    uniIcons
  },
  data() {
    return {
      productId: 0,
      detail: {},
      recommend: [],
      columnWidth: 150
    };
  },
  onLoad(options) {
      // 添加登录状态检查
      const userId = uni.getStorageSync("userId");
      
      // 获取传递的商品ID
      if (options.id) {
        this.productId = options.id;
        this.fetchProductDetail();
      }
      
      // 计算瀑布流列宽
      const systemInfo = uni.getSystemInfoSync();
      // 假设左右间距各10px，中间间距10px
      this.columnWidth = (systemInfo.windowWidth - 30) / 2;
    },
  computed: {
    leftColumn() {
      return this.recommend.filter((item, index) => index % 2 === 0);
    },
    rightColumn() {
      return this.recommend.filter((item, index) => index % 2 === 1);
    },
    // 计算处理后的图片URL
    processedMainImage() {
      return this.getFullImageUrl(this.detail.img);
    }
  },
  methods: {
    // 获取商品详情
    // 获取商品详情
    fetchProductDetail() {
      foodAPI.getProductDetail({
        id: this.productId
      }).then((res) => {
        if (res.data.code === 1) {
          this.detail = res.data.data.detail || {};
          this.recommend = res.data.data.recommend || [];
          
          // 处理图片路径
          if (this.detail.img && !this.detail.img.startsWith("http")) {
            this.detail.img = config.baseURL + this.detail.img;
          }
          
          // 处理推荐商品图片路径
          this.recommend.forEach((item) => {
            if (item.img && !item.img.startsWith("http")) {
              item.img = config.baseURL + item.img;
            }
          });
          
        } else {
          uni.showToast({
            title: res.data.msg || "获取数据失败",
            icon: "none",
          });
        }
      }).catch((err) => {
        uni.showToast({
          title: "网络请求失败",
          icon: "none",
        });
        console.error("请求商品详情失败:", err);
      });
    },
    
    // 切换到另一个商品（点击推荐商品时调用）
    switchToProduct(productId) {
      this.productId = productId;
      this.fetchProductDetail();
    },
    
    // 获取完整的图片URL
    getFullImageUrl(imgUrl) {
      if (!imgUrl) return '';

      // 如果已经是完整URL，直接返回
      if (/^https?:\/\//i.test(imgUrl)) {
        return imgUrl;
      }

      // 处理相对路径
      let cleanUrl = imgUrl;
      const baseUrl = config.baseURL;
      
      // 移除可能重复的基础URL
      while (cleanUrl.startsWith(baseUrl)) {
        cleanUrl = cleanUrl.substring(baseUrl.length);
      }

      // 构造完整URL
      if (cleanUrl.startsWith('/')) {
        return baseUrl + cleanUrl;
      }
      return baseUrl + '/' + cleanUrl;
    },
    
    // 获取商品图片
    getProductImage(product) {
      if (product.img && product.img !== '') {
        // 处理图片路径
        return this.getFullImageUrl(product.img);
      }
      // 没有图片时返回空
      return "";
    },

    // 获取商品标题
    getProductTitle(product) {
      if (product.title) {
        return product.title;
      }
      return "未知商品";
    },

    // 获取商品详情
    getProductNotice(product) {
      if (product.notice) {
        return product.notice;
      }
      return "暂无详情";
    },

    // 获取商品销量
    getProductQuantity(product) {
      if (product.quantity) {
        return product.quantity;
      }
      return 0;
    },

    // 获取商品价格
    getProductPrice(product) {
      if (product.money) {
        return product.money;
      }
      if (product.price) {
        return product.price;
      }
      return "0";
    },

    // 获取商品原价
    getProductOriginalPrice(product) {
      const price = this.getProductPrice(product);
      // 这里简单地将原价设置为现价的1.2倍
      return (parseFloat(price) * 1.2).toFixed(2);
    },
    
    // 返回上一页
    goBack() {
      uni.navigateBack();
    },
    

    // 预览图片
    previewImage(url) {
      uni.previewImage({
        urls: [url],
        current: 0
      });
    },
    
    // 点击返回店铺
    toShop() {
      uni.navigateTo({
        url: "/pages/shop/shop"
      });
    },
    
    // 立即购买处理函数
    handleBuyNow() {
      // 检查是否登录
      const userId = uni.getStorageSync("userId");
      
      // 添加更全面的登录状态检查
      if (!userId || userId === '' || userId === 'undefined' || userId === 'null') {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        });
        
        setTimeout(() => {
          uni.navigateTo({
            url: '/pages/login/login'
          });
        }, 1000);
        return;
      }
      
      // 保存商品信息到本地存储
      try {
        uni.setStorageSync('selectedProduct', this.detail);
        
        // 跳转到订单提交页面
        uni.navigateTo({
          url: '/pages/goodsorder/goodsorder'
        });
      } catch (error) {
        console.error('保存商品信息失败:', error);
        uni.showToast({
          title: '操作失败，请重试',
          icon: 'none'
        });
      }
    }
  }
};
</script>

<style scoped>
.container {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 20rpx;
  position: relative;
}

.navbar {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 88rpx;
  background-color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20rpx;
  box-sizing: border-box;
  z-index: 999;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.nav-button {
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.nav-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
}

.image-container {
  width: 100%;
  height: 400rpx;
  overflow: hidden;
}

.product-image {
  width: 100%;
  height: 400rpx;
}

.product-card {
  width: 90%;
  margin: -80rpx auto 20rpx;
  background-color: #ffffff;
  border-radius: 20rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  box-sizing: border-box;
  position: relative;
  z-index: 10;
}

.product-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333333;
  margin-bottom: 20rpx;
}

.product-sales {
  font-size: 28rpx;
  color: #999999;
  margin-bottom: 30rpx;
}

.product-price-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price-section {
  display: flex;
  align-items: baseline;
}

.price {
  font-size: 40rpx;
  font-weight: bold;
  color: #FF8D1A;
}

.add-to-cart {
  background-color: #FF8D1A;
  border-radius: 40rpx;
  padding: 15rpx 30rpx;
}

.add-text {
  font-size: 28rpx;
  color: #ffffff;
  font-weight: bold;
}

.product-description {
  background-color: #ffffff;
  margin: 20rpx;
  border-radius: 20rpx;
  padding: 30rpx;
}

.desc-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
  margin-bottom: 20rpx;
}

.desc-content {
  font-size: 28rpx;
  color: #666666;
  line-height: 1.6;
}

.recommend-section {
  padding: 0 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
  margin: 20rpx 0;
}

.waterfall-content {
  display: flex;
  justify-content: space-between;
}

.waterfall-column {
  display: flex;
  flex-direction: column;
}

.waterfall-item {
  width: 95%;
  background-color: #ffffff;
  border-radius: 15rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.item-image {
  width: 100%;
  height: 210rpx;
}

.item-info {
  padding: 15rpx;
}

.item-title {
  font-size: 26rpx;
  color: #333333;
  margin-bottom: 10rpx;
  display: block;
  font-weight: bold;
}

.item-details-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10rpx;
}

.item-notice {
  font-size: 22rpx;
  color: #666666;
  flex: 0 0 45%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.item-quantity {
  font-size: 22rpx;
  color: #999999;
  text-align: right;
  flex: 1;
  margin-left: 10rpx;
}

.item-price-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.item-price {
  font-size: 30rpx;
  color: #FF8D1A;
  font-weight: bold;
}

.item-original-price {
  font-size: 24rpx;
  color: #999999;
  text-decoration: line-through;
}

/* 底部操作按钮 */
.footer_box {
  width: 100%;
  height: 60px;
  position: fixed;
  bottom: 0;
  background-color: white;
  display: flex;
  justify-content: space-between;
  border-top: 1px solid #f5f5f5;
  z-index: 100;
}

.operate_box {
  width: 30%;
  display: flex;
  justify-content: space-evenly;
}

.goods_actions {
  width: 20%;
}

.operate_img {
  width: 35px;
  height: 35px;
  margin-top: 50%;
  margin-left: 14%;
}

.buyButton_box {
  width: 61%;
  margin-right: 5%;
}

.buy-now-btn {
  margin-top: 5%;
  height: 35px;
  line-height: 35px;
  background-color: #FF8D1A;
  color: white;
  border-radius: 20px;
  border: none;
  font-size: 14px;
}

.footer-placeholder {
  height: 80px;
}
</style>